package com.appistry.api.rest.httpcommons;

import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FabricManagerHttpMethodRetryHandler extends DefaultHttpMethodRetryHandler {
	private static final Log LOG = LogFactory.getLog(FabricManagerHttpMethodRetryHandler.class);
	private long millisecondDelay;

	public FabricManagerHttpMethodRetryHandler(int retryCount, long millisecondDelay) {
		super(retryCount, true);
		this.millisecondDelay = millisecondDelay;
	}

	@Override
	public boolean retryMethod(final HttpMethod method, final IOException exception, int executionCount) {
		if (millisecondDelay > 0) {
			sleep(this.millisecondDelay);
		}
		return super.retryMethod(method, exception, executionCount);
	}

	private static void sleep(long millisecondDelay) {
		try {
			LOG.debug("Sleeping " + millisecondDelay + "ms before retrying httpd call.");
			Thread.sleep(millisecondDelay);

		} catch (Exception e) {
			LOG.error("Unable to sleep before retry http method!", e);
		}
	}

}
